package bzimerman.media.myflix;

import android.app.Activity;
import android.os.Bundle;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;

import org.apache.commons.io.comparator.LastModifiedFileComparator;
import org.apache.commons.io.comparator.NameFileComparator;
import org.apache.commons.io.comparator.PathFileComparator;
import org.apache.commons.io.comparator.SizeFileComparator;

public class MyFlixActivity extends ListActivity {
	
    /** Called when the activity is first created. */
	private enum DISPLAYMODE{ ABSOLUTE, RELATIVE; }
	sorterHelper sorty = new sorterHelper();
	
    private final DISPLAYMODE displayMode = DISPLAYMODE.RELATIVE;
    private List<String> directoryEntries = new ArrayList<String>();
    private File currentDirectory = new File("/");
    public String path;
    File selected;
    movieDatabase database;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
            super.onCreate(icicle);
            database = new movieDatabase(this);
            selected = null;
            // setContentView() gets called within the next line,
            // so we do not need it here.
            browseToRoot();
    }
   
    /**
     * This function browses to the
     * root-directory of the file-system.
     */
    private void browseToRoot() {
            browseTo(new File("/"));
}
   
    /**
     * This function browses up one level
     * according to the field: currentDirectory
     */
    private void upOneLevel(){
            if(this.currentDirectory.getParent() != null)
                    this.browseTo(this.currentDirectory.getParentFile());
    }
   
    private void browseTo(final File aDirectory){
    		final String path = aDirectory.getAbsolutePath().toLowerCase();
    		//System.out.println(path);
    		
            if (aDirectory.isDirectory()){
                    this.currentDirectory = aDirectory;
                    //System.out.println(aDirectory.listFiles());
                    fill(aDirectory.listFiles());
            }else{
                    OnClickListener okButtonListener = new OnClickListener(){
                            // @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                            if(	   path.contains(".jpg") || path.contains(".png") 
                            	|| path.contains(".gif")){
                            	Intent intent = new Intent();
                            	intent.setAction(android.content.Intent.ACTION_VIEW);
                            	intent.setDataAndType(Uri.fromFile(new File(aDirectory.getAbsolutePath())), "image/*");
                            	startActivity(intent);
                            }
                            else if (  path.contains(".wmv") || path.contains(".mp4") 
                            		|| path.contains(".avi") || path.contains(".divx")
                            		|| path.contains(".fv4") || path.contains(".mov")
                            		|| path.contains(".moov")|| path.contains(".mpeg4")
                            		|| path.contains(".ogv") || path.contains(".xvid")
                            		|| path.contains(".mpg") || path.contains(".mpeg")
                            		|| path.contains(".mkv") || path.contains(".flv")
                            		|| path.contains(".m4v")){
                            	//This makes a custom video player because the default player is shit
                            	Intent intent = new Intent(getBaseContext(), myMediaPlayer.class);
                            	//System.out.println(path);
                            	intent.putExtra("PATH_ID", aDirectory.getAbsolutePath());
                            	startActivity(intent);
                            	//Intent intent = new Intent();
                            	//intent.setAction(android.content.Intent.ACTION_VIEW);
                            	//intent.setDataAndType(Uri.fromFile(new File(aDirectory.getAbsolutePath())), "video/*");
                            	//startActivity(intent);
                            }
                            else if (  path.contains(".ogg")|| path.contains(".mp3")
                            		|| path.contains(".wav")|| path.contains(".flac")){
                            	Intent intent = new Intent();
                            	intent.setAction(android.content.Intent.ACTION_VIEW);
                            	intent.setDataAndType(Uri.fromFile(new File(aDirectory.getAbsolutePath())), "audio/*");
                            	startActivity(intent);
                            }
                            }
                    };
                    OnClickListener cancelButtonListener = new OnClickListener(){
                            // @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                                    // Do nothing
                            }
                    };
                    new AlertDialog.Builder(this)
                    .setTitle("Question")
                    .setMessage("Do you want to open that file?\n"+ aDirectory.getName())
                    .setPositiveButton("OK", okButtonListener)
                    .setNegativeButton("Cancel", cancelButtonListener)
                    .show();
            }
    }
    
    private String toLowerCase(String path) {
		// TODO Auto-generated method stub
		return null;
	}

	private void fill(File[] files){
    		final File sortDirectory = currentDirectory;
    		
            this.directoryEntries.clear();
           
            // Add the "." and the ".." == 'Up one level'
            try {
                    Thread.sleep(10);
            } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
            }
            this.directoryEntries.add(".");
           
            if(this.currentDirectory.getParent() != null)
                    this.directoryEntries.add("..");
           
            files = sorty.fileSort(files);
            
            switch(this.displayMode){
                    case ABSOLUTE:
                    		if(files != null){
                    		for (File file : files){
                    			if(file!=null){
                                   this.directoryEntries.add(file.getPath());
                    			}
                    		}
                    		}
                            break;
                    case RELATIVE: // On relative Mode, we have to add the current-path to the beginning
                            int currentPathStringLenght = this.currentDirectory.getAbsolutePath().length();
                            if(files != null){
                            for (File file : files){
                            	if(file!=null){
                                    this.directoryEntries.add(file.getAbsolutePath().substring(currentPathStringLenght));
                            	}
                            }
                            }
                            break;
            }
           
            ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this,
                            R.layout.file_row, this.directoryEntries);
           
            //this.setListAdapter(directoryList);
            
            final View vg = findViewById(R.layout.browser_screen);
            this.setContentView(R.layout.browser_screen);
            
        	
        	RadioGroup sortRadio = (RadioGroup) findViewById(R.id.radioGroupSort);
        	switch(sorty.getSorter()){
        		case 0:sortRadio.check(R.id.Name);
        			break;
        		case 1:sortRadio.check(R.id.Type);
        			break;
        		case 2:sortRadio.check(R.id.Modified);
        			break;
        		case 3:sortRadio.check(R.id.Size);
        			break;
        	}
        	
        	sortRadio.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) { 
                    RadioButton radioButton = (RadioButton) findViewById(checkedId);
                    //System.out.println(radioButton.getId());
                    //System.out.println(R.id.Name);
                    switch (radioButton.getId()) {
        		    case R.id.Name:
        		    	sorty.setSorter(0);
        		    	browseTo(sortDirectory);
        		        break;
        		    case R.id.Type:
        		    	sorty.setSorter(1);
        		    	browseTo(sortDirectory);
        		    	break;
        		    case R.id.Modified:
        		    	sorty.setSorter(2);
        		    	browseTo(sortDirectory);
        		    	break;
        		    case R.id.Size:
        		    	sorty.setSorter(3);
        		    	browseTo(sortDirectory);
        		    	break;
        		    default:
        		    	break;
        		    }
                }
        	});

        	
            ListView fileList = (ListView) findViewById(android.R.id.list);
            TextView someText = (TextView) findViewById(R.id.infoview);
            someText.setText("Current Location:\n" + this.currentDirectory.getAbsolutePath());
            path = this.currentDirectory.getAbsolutePath();
            RatingBar rating = (RatingBar) findViewById(R.id.ratingsBar);
            
            try {
				rating.setNumStars(getStars());
			} catch (NoSuchAlgorithmException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

            rating.setOnRatingBarChangeListener(new OnRatingBarChangeListener(){

				@Override
				public void onRatingChanged(RatingBar arg0, float stars, boolean touched) {
					if (touched){

						try {
							database.InsertMovie(selected.toString(), path, "", (int) stars, 0, "");
						} catch (NoSuchAlgorithmException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					
				}
            });
            
            fileList.setAdapter(directoryList);
            
    }

	public int getStars() throws NoSuchAlgorithmException, UnsupportedEncodingException{
		int rating = 0;
		if (selected != null && path != null){
			rating = database.returnRating(selected.toString(), path);
		}
		return rating;
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
	    	if(this.currentDirectory.getParent() == null){
	    		moveTaskToBack(true);
	    	}else{
	    		this.upOneLevel();
	    	}
	        return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
    protected void onListItemClick(ListView l, View v, int position, long id) {
            String selectedFileString = this.directoryEntries.get(position);
            //System.out.println(position);
            //System.out.println(selectedFileString);
            if (selectedFileString.equals(".")) {
                    // Refresh
                    this.browseTo(this.currentDirectory);
            } else if(selectedFileString.equals("..")){
                    this.upOneLevel();
            } else {
                    File clickedFile = null;
                    switch(this.displayMode){
                            case RELATIVE:
                                    clickedFile = new File(this.currentDirectory.getAbsolutePath()
                                                                                            + this.directoryEntries.get(position));
                                    break;
                            case ABSOLUTE:
                                    clickedFile = new File(this.directoryEntries.get(position));
                                    break;
                    }
                    if(clickedFile != null && (clickedFile.isDirectory() || clickedFile.equals(selected))){
                            this.browseTo(clickedFile);
                            selected = null;
                    }else{
                    	selected = clickedFile;
                    }
            }
    }
    
    /*@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	    case R.id.name:
	    	sortMode = SORTMODE.NAME;
	        return true;
	    case R.id.type:
	    	sortMode = SORTMODE.TYPE;
	        return true;
	    case R.id.modified:
	    	sortMode = SORTMODE.MODIFIED;
	        return true;
	    case R.id.size:
	    	sortMode = SORTMODE.SIZE;
	        return true;
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}*/
    
}